package Pathall;


import Activemq.Node;
import Redis.Rdo;

import java.util.*;

public class BFS implements PathPlanner {
    // 方向枚举 - 上下左右
    private enum Direction {
        UP(-1, 0),
        DOWN(1, 0),
        LEFT(0, -1),
        RIGHT(0, 1);

        public final int deltaX;
        public final int deltaY;

        Direction(int deltaX, int deltaY) {
            this.deltaX = deltaX;
            this.deltaY = deltaY;
        }
    }

    @Override
    public List<int[]> findPath(int[] start, int[] end, Rdo rdo, int mapWidth, int mapHeight) {
        // 参数检查
        if (start == null || end == null) return new ArrayList<>();
        if (!isValidCoordinate(end[0], end[1], mapWidth, mapHeight)) return new ArrayList<>();

        // 创建队列和父节点映射
        Queue<int[]> queue = new LinkedList<>();
        Map<String, int[]> parentMap = new HashMap<>();
        Set<String> visited = new HashSet<>();

        // 起点处理
        queue.add(start);
        visited.add(start[0] + "," + start[1]);

        while (!queue.isEmpty()) {
            int[] current = queue.poll();

            // 检查是否到达终点
            if (current[0] == end[0] && current[1] == end[1]) {
                return reconstructPath(parentMap, end);
            }

            // 探索所有方向
            for (Direction dir : Direction.values()) {
                int neighborX = current[0] + dir.deltaX;
                int neighborY = current[1] + dir.deltaY;
                String neighborKey = neighborX + "," + neighborY;

                // 检查坐标有效性
                if (!isValidCoordinate(neighborX, neighborY, mapWidth, mapHeight))
                    continue;

                // 跳过已访问节点
                if (visited.contains(neighborKey))
                    continue;

                // 关键修改：仅当不是终点时才检查障碍物
                boolean isGoal = (neighborX == end[0] && neighborY == end[1]);
                if (!isGoal && rdo.checkobstacle(neighborX, neighborY))
                    continue;

                // 添加到访问集合和队列
                visited.add(neighborKey);
                int[] neighbor = {neighborX, neighborY};
                parentMap.put(neighborKey, current);
                queue.add(neighbor);
            }
        }

        return new ArrayList<>(); // 没有找到路径
    }

    // 重建路径
    private List<int[]> reconstructPath(Map<String, int[]> parentMap, int[] end) {
        LinkedList<int[]> path = new LinkedList<>();
        int[] current = end;

        while (current != null) {
            path.addFirst(current); // 从终点反向构建路径
            String key = current[0] + "," + current[1];
            current = parentMap.get(key);
        }

        return path;
    }

    // 坐标有效性检查
    private boolean isValidCoordinate(int x, int y, int mapWidth, int mapHeight) {
        return x >= 0 && x < mapWidth && y >= 0 && y < mapHeight;
    }
}
